package com.yangyuhao.haowuyoupin.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "haowuyoupin.db";
    private static final int DATABASE_VERSION = 2;

    // 用户表
    public static final String TABLE_USERS = "users";
    
    // 用户表字段
    public static final String COLUMN_ACCOUNT = "account";          // 账号
    public static final String COLUMN_PASSWORD = "password";        // 密码
    public static final String COLUMN_NICKNAME = "nickname";        // 昵称
    public static final String COLUMN_IS_LOGIN = "is_login";       // 登录状态
    public static final String COLUMN_CREDIT_SCORE = "credit_score"; // 交易信誉
    public static final String COLUMN_IS_ADMIN = "is_admin";       // 是否是管理员
    public static final String COLUMN_EXTRA = "extra";             // 冗余字段

    // 创建用户表的 SQL 语句
    private static final String CREATE_TABLE_USERS = 
        "CREATE TABLE " + TABLE_USERS + " (" +
        COLUMN_ACCOUNT + " TEXT PRIMARY KEY," +
        COLUMN_PASSWORD + " TEXT NOT NULL," +
        COLUMN_NICKNAME + " TEXT," +
        COLUMN_IS_LOGIN + " INTEGER DEFAULT 0," +  // 0表示未登录，1表示已登录
        COLUMN_CREDIT_SCORE + " INTEGER DEFAULT 100," +
        COLUMN_IS_ADMIN + " INTEGER DEFAULT 0," +  // 0表示普通用户，1表示管理员
        COLUMN_EXTRA + " TEXT" +
        ")";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建用户表
        db.execSQL(CREATE_TABLE_USERS);
        
        // 插入管理员数据
        ContentValues adminValues = new ContentValues();
        adminValues.put(COLUMN_ACCOUNT, "admin");
        adminValues.put(COLUMN_PASSWORD, "admin123"); // 建议使用加密后的密码
        adminValues.put(COLUMN_NICKNAME, "管理员");
        adminValues.put(COLUMN_IS_ADMIN, 1);
        adminValues.put(COLUMN_CREDIT_SCORE, 100);
        
        db.insert(TABLE_USERS, null, adminValues);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 如果需要升级数据库，在这里处理
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
        onCreate(db);
    }
} 